//
//  PieCharView.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/6/12.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit

class PieCharView: UIView {

    //MARK:--
    var valueStore:[String]!
    var titleStore:[String]!
    //选中某一个值或者取消某一个值的回调
//    var callBack:(index:Int,selectSign:Bool) ->Void!
    var callBack:((index:Int, selectSign:Bool) -> Void)!
    //颜色值
    var colorStore:[UIColor]!
    //整个收入和其title
    var sumIncome:CGFloat!
    var title:String!
    
    //layer
    var layerStore:[CAShapeLayer] = [CAShapeLayer]()////层 layer数组
    var percentStore:[CGFloat] = [CGFloat]()//百分比
    var endAngleStore:[CGFloat] = [CGFloat]()// 结束角度数组
    
    //圆
    var pieCharCenter:CGPoint!//中心点
    var radius:CGFloat!//半径
    var lineWidth:CGFloat!//线宽
    
    
    var selectLineWidth:CGFloat!//选中时的线宽
    var selectIndex:Int = -1 //选中的layer的下标默认为-1
    
    //动画时长
    var duratio:CGFloat! = 0.5
    
    //中心点收入label
    var centerIncomeLabel:UILabel!
    //中心点的titlelabel
    var centerTitleLabel:UILabel!
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        let width = CGRectGetWidth(frame)
        let height = CGRectGetHeight(frame)
        let minWidth = height > width ? width : height
        
        pieCharCenter = CGPointMake(width/2,height/2)
        radius = minWidth * 0.25
        lineWidth = minWidth * 0.25
        selectLineWidth = minWidth * 0.28
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    
    //MARK:--
    //绘图方法
    func stroke(){
        
        getSumValueAndPercent()//数据
        
        //添加layer
        createShapeLayer()
        
        //添加中心点的收入label 和titlelabel
        createLabels()
    }
    
    
    func createLabels(){
        
        centerIncomeLabel = UILabel(frame: CGRectMake(0,0,radius*1.2,30))
        centerIncomeLabel.font = UIFont.boldSystemFontOfSize(20)
        centerIncomeLabel.textAlignment = .Center
        centerIncomeLabel.text = NSString(format: "%2f", sumIncome) as String
        addSubview(centerIncomeLabel)
        
        centerTitleLabel =  UILabel(frame: CGRectMake(0,0,radius*1.2,20))
        centerTitleLabel.font = UIFont.boldSystemFontOfSize(13)
        centerTitleLabel.textAlignment = .Center
        centerTitleLabel.text = title
        addSubview(centerTitleLabel)
        
        //设置中心点
        centerIncomeLabel.center = CGPointMake(pieCharCenter.x, pieCharCenter.y-30)
        centerTitleLabel.center = CGPointMake(pieCharCenter.x, pieCharCenter.y+10)
        
    }
    
    
    
    //数据 ~得到总value值，以及对应value的比例
    func getSumValueAndPercent(){
        sumIncome = 0
        for value in valueStore{
            sumIncome = sumIncome + CGFloat(value.floatValue!)
            
        }
        
        if sumIncome == 0{
            return
        }
        
        for value in valueStore{
            let valueCGFloat = CGFloat(value.floatValue!)
            percentStore.append(valueCGFloat/sumIncome)
            
        }
        
    }
    
    
    //添加layer
    func createShapeLayer(){
        //比例
        var startAngle:CGFloat = 0
        var endAngle:CGFloat = 0
        
        
        var animationDelay:CGFloat = 0
        for i in 0..<(valueStore.count){
            
            let angle = CGFloat(M_PI * 2.0) * CGFloat(percentStore[i])
            endAngle = startAngle + angle
            endAngleStore.append(endAngle)
            
            var paramDic = [String:AnyObject]()
            paramDic["start"] = String(startAngle)
            paramDic["end"] = String(endAngle)
            paramDic["index"] = String(i)//取颜色用的or层
            paramDic["lineWidth"] = String(lineWidth)
            paramDic["animation"] = NSNumber(bool:true)//有无动画
            
            let label = UILabel(frame: CGRectMake(0,0,70,20))
            label.font = UIFont.boldSystemFontOfSize(16)
            label.textColor = UIColor.whiteColor()
            label.center = labelCenter(startAngle, end: endAngle)
            label.text = NSString(format: "%.0f%%", percentStore[i]*100) as String
            addSubview(label)
            
            self.performSelector("addLayer:",withObject: paramDic,afterDelay: Double(animationDelay))
            animationDelay = animationDelay +  percentStore[i] * duratio
            startAngle = endAngle
        
        }
    
    }
    
    
    func labelCenter(start:CGFloat,end:CGFloat) -> CGPoint{
        let half = (start + end) / 2
        let center_x = cos(half) * radius + pieCharCenter.x
        let center_y = sin(half) * radius + pieCharCenter.y
        
        return CGPointMake(center_x,center_y)
        
    }
 
    //
    func addLayer(param:[String:AnyObject]){
        
        let shapelayer = CAShapeLayer()//创建一个层
        let bezierPath = UIBezierPath()//bezierPath路径
        
        //
        let start = CGFloat((param["start"]?.floatValue)!)
        let end = CGFloat((param["end"]?.floatValue)!)
        let lineWidth = CGFloat((param["lineWidth"]?.floatValue)!)
        let index = Int(param["index"]!.floatValue)
        let animation = (param["animation"] as! NSNumber).boolValue
  
        
        
        
        //1.圆弧，2半径，3开始的弧度，4结束的弧度，5顺时针，逆时针
        bezierPath.addArcWithCenter(pieCharCenter, radius: radius, startAngle: start, endAngle: end, clockwise: true)
        
        shapelayer.path = bezierPath.CGPath//路径
        shapelayer.lineWidth = lineWidth//线宽
        shapelayer.strokeColor = colorStore[index].CGColor//线颜色
        shapelayer.fillColor = UIColor.clearColor().CGColor//填充颜色
        
        shapelayer.shadowColor = UIColor.lightGrayColor().CGColor//阴影
        shapelayer.shadowOffset = CGSizeMake(1, 1)
        shapelayer.shadowOpacity = 1.0
        
        //如果有动画动画
        if animation{
            //添加动画
            shapelayer.addAnimation(creatAnimation(index), forKey: "00")
        }
        
        self.layer.insertSublayer(shapelayer, atIndex: 0)
        if layerStore.count > index{
            //替换
            layerStore.replaceRange(Range(start: layerStore.startIndex.advancedBy(index), end: layerStore.startIndex.advancedBy(index + 1)), with: [shapelayer])
        }else{
            layerStore.append(shapelayer)
        }
    }
    
    //添加动画
    func creatAnimation(index:Int) -> CABasicAnimation{
        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        basicAnimation.duration = Double(percentStore[index] * duratio)
        //匀速的动画效果
        basicAnimation.timingFunction = CAMediaTimingFunction(name: "linear")
        //结束时的状态
        basicAnimation.fillMode = "forwards"
        basicAnimation.removedOnCompletion = false
        basicAnimation.fromValue = 0
        basicAnimation.toValue = 1
        
       return basicAnimation
        
    }
    
    
    //MARK:===touch
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        let touch = touches.first
        let point = (touch?.locationInView(self))!
        
        //点到圆环的距离
        let dis_x = point.x - pieCharCenter.x
        let dis_y = point.y - pieCharCenter.y
        let radius_x = sqrt(pow(dis_x, 2) + pow(dis_y,2))
        //在圆环范围之外
        if radius_x > radius + selectLineWidth / 2 || radius < radius - selectLineWidth / 2{
            return
        }else{
            /*
            atan2(y,x) 得到(x,y)与x轴的夹角，点(x,y)与原点的连线与x轴的夹角，范围是-M_PI到M_PI
            结果为正，0~M_PI,顺时针
            结果为负，-M_PI~0,逆时针
            */
            var angle = atan2(dis_y, dis_x)
            //结果为负，上半圆时，调整成正值
            if angle < 0{
                angle = angle + CGFloat(M_PI * 2)
        }
        let index = findAngle(angle)
        tapLayerByIndex(index)
        
       
    }
        
   }
    func tapLayerByIndex(index:Int){
        if selectIndex != -1{
            //判断之前选中过一个layer
            //改变之前选中的layer
            selectOrNotLayer(selectIndex)
            if selectIndex == index{
                //重复选中变成非选中
                 self.callBack(index:index,selectSign:false)
                centerIncomeLabel.text = NSString(format: "%.2f", sumIncome) as String
                centerTitleLabel.text = title
                selectIndex = -1
                return
            }
        }
        //将现在点击的变成选中的状态
        selectOrNotLayer(index)
        centerIncomeLabel.text = NSString(format: "%.2f", valueStore[index].floatValue!) as String
        centerTitleLabel.text = titleStore[index]
        selectIndex = index
        self.callBack(index:index,selectSign:true)
        
    }
   
    
    
    //判断之前选中过一个layer
    func selectOrNotLayer(index:Int){
        var lineWidth_x = lineWidth
        var startAngle:CGFloat = 0
        var endAngle = endAngleStore[index]
        if index > 0{
            startAngle = endAngleStore[index-1]
        }
        let currentlayer = layerStore[index]
        if currentlayer.lineWidth < selectLineWidth{
            lineWidth_x = selectLineWidth
            startAngle = startAngle + 0.1
            endAngle = endAngle - 0.1
        }
        UIView.animateWithDuration(0.3) { () -> Void in
            currentlayer.lineWidth = lineWidth_x
            let beziePath = UIBezierPath()
            beziePath.addArcWithCenter(self.pieCharCenter, radius: self.radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            currentlayer.path = beziePath.CGPath
            
        }
    }
    
    
    //找到弧度对应的layer下标
    func findAngle(angle:CGFloat) -> Int{
        
        for i in 0..<(endAngleStore.count){
            
            if endAngleStore[i]>angle{
                return i
            }
        }
        return 0
    }
    
    
}
